package cc.risingsun.wing.core.reflect;

import java.lang.annotation.Annotation;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Map;

import cc.risingsun.wing.core.ASMUtil;
import cc.risingsun.wing.ds.DataStruct;

/**
 * 反射辅助类
 * 
 * @author iron.yin@gmail.com
 */
public final class ReflectionHelper {

	private ReflectionHelper() {
	}

	public static Class<?> getClassOnClassLoader(String name, ClassLoader classLoader) throws ClassNotFoundException {
		if (classLoader != null) {
			try {
				return Class.forName(name, false, classLoader);
			} catch (ClassNotFoundException e) {
			}
		}
		return Class.forName(name);
	}

	/**
	 * 获取当前线程上下文类加载器
	 * 
	 * @return
	 */
	public static ClassLoader getContextClassLoader() {
		return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
			@Override
			public ClassLoader run() {
				ClassLoader classLoader = null;
				try {
					classLoader = Thread.currentThread().getContextClassLoader();
				} catch (SecurityException e) {
				}
				return classLoader;
			}
		});
	}

	public static Map<String, Class<? extends Annotation>> getAnnotations(Class<? extends Annotation>... annotations) {
		if (annotations == null)
			return null;
		Map<String, Class<? extends Annotation>> annotationClasses = DataStruct.hashMap(annotations.length);
		String key;
		for (Class<? extends Annotation> c : annotations) {
			key = "L" + ASMUtil.obverse(c.getName()) + ";";
			if (!annotationClasses.containsKey(key))
				annotationClasses.put(key, c);
		}
		return annotationClasses;
	}

	public static Class<?> classForNameWithException(String name, ClassLoader cl) throws ClassNotFoundException {
		if (cl != null) {
			try {
				return Class.forName(name, false, cl);
			} catch (ClassNotFoundException ex) {
			}
		}
		return Class.forName(name);
	}

}
